<template>
  <div class="index">
    <div class="shop-list">
			<div class="search-top">
				<!-- <img class="logo" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQfSVKuRdY-U2bQOZnNYtHezWNo4KkZQmJshj32gMp86Q&s"/> -->
				<image class="logo" mode="aspectFill" :src="icon.logo"/>
				<div class="search">
          <u-search
          :show-action="false"
          :animation="true"
					shape="square"
          disabled
          @click="goSearch"
        ></u-search>
				</div>
			</div>
    	<!-- 商品列表 -->
			<div class="content">
				<div class="tabs">
					<div class="tab" v-for="(tab,index) in tabs" :key="index" :class="active === index ? 'act-tab' : ''" @click="changeTab(index)">
						<span>{{tab.name}}</span>
						<img v-if="active === index" mode="aspectFill" :src="icon.act" class="active"/>
					</div>
				</div>
				<!-- 二级分类 -->
				<div class="second-tabs">
					<div class="top">
						<div class="h3">{{tabs[active].name}}</div>
						<div class="second-tabs-li" :class="showModal ? 'show-second-tabs-li' : ''">
							<div class="lis">
								<div class="li" v-for="(tab,index) in secondTabs" :key="index" :class="secondTab === index ? 'sec-act-tab' : ''" @click="changeSecTab(index)">{{tab.name}}</div>
							</div>
							<u-icon class="icon" v-if="secondTabs.length>3" name="arrow-down-fill" color="#333" size="14" @click="changeModal"></u-icon>
						</div>
					</div>
					<scroll-view class="list"
						:scroll-y="true"
						:refresher-enabled="true"
						:enable-back-to-top="true"
						:scroll-anchoring="true"
						:refresher-triggered="triggered"
						@refresherrefresh="onRefresh"
						@scrolltolower="onLower">
					<div class="modals" v-if="showModal" @click="changeModal"></div>
						<div class="shop-li" v-for="(item,index) in goodsList" :key="index" @click="goDetail(item.spuCode)">
							<image :src="item.coverImage" class="img"/>
							<div class="shop-content">
								<div class="title">{{item.productName}}</div>
								<div class="num" v-if="item.originalPrice">￥{{item.originalPrice }}</div>
								<div class="kc">库存：{{ item.stockNum || 0 }} {{ item.unit || '件' }}</div>
								<div class="bottom">
									<div class="left" v-if="auth_token">
										<div class="vip">
											<img v-if="levelName" :src="icon.vip" alt="">
											<span>{{levelName || '普通用户'}}</span>
										</div>
										<div class="money">￥{{item.salesPrice}}</div>
									</div>
									<div class="left" v-else>
										<div class="vip logins">登录查看价格</div>
									</div>
									<image v-if="auth_token" class="icon" :src="item.stockNum ? icon.exchange : icon.no_exchange" @click.stop="showSku(item.spuCode)"/>
								</div>
							</div>
						</div>
						<div class="diver" v-if="finished && goodsList.length">
							<u-divider text="没有更多了"></u-divider>
						</div>
						<div class="empty" v-if="!goodsList.length">
							<u-empty mode="data" text="暂无商品"></u-empty>
						</div>
					</scroll-view>
				</div>
			</div>
    </div>
			<!-- 弹出框Sku -->
		<u-popup :show="showSkuModal" mode="bottom" :round="16" @close="close">
      <sku-modal v-if="showSkuModal" :productSpecsList="goodsInfo.productSpecsList" @goOrder="goOrder"></sku-modal>
    </u-popup>
		<privacyPopup :showPop="showPop" exitApp inTabPage @handle="popBtnTap"></privacyPopup>
  </div>
</template>

<script>
import auth from '../../api/auth'
import { formatNumber } from '../../utils/index.js'
import SearchInput from '../../components/SearchInput.vue'
import SkuModal from '../../components/SkuModal.vue'

export default {
	components:{
		SearchInput,
		SkuModal
	},
  data() {
    return {
			icon:{
				logo: require('./static/logo.png'),
				exchange: require('../../static/exchange-icon.png'),
				no_exchange: require('../../static/no-exchange-icon.png'),
				vip:require('../../static/vip-icon.png'),
				act:require('../../static/active-icon.png'),
			},
			showPop: false,
			showSkuModal: false,
			showModal: false,
			triggered: false,
			finished: false,
			active:0,
			secondTab:0,
			tabs:[],
			secondTabs: [],
			goodsList:[],
			goodsInfo: {
        pic: [],
      },
			pageNum:1,
			goodsCount:0,
			firstId:0,
			secondId:0,
			auth:null,
			auth_token:null,
			levelName: ''

		}
  },
  async onLoad() {
		
		// 隐私协议
		const privacySettingRes = await this.getPrivacySetting();
		console.log()
		this.showPop = privacySettingRes.needAuthorization
		this.getClassifyList(0)
		
	},
	async onShow() {
		this.auth = uni.getStorageSync('_AUTH_')
		this.auth_token = uni.getStorageSync('AUTH_TOKEN')
		if(this.auth_token) {
			this.memberGetUserInfo()
		}
	},
  methods: {
		 /**
		 * 按钮点击回调
		 */
		popBtnTap(res) {
			if (res.detail.result) {
				uni.showToast({
					title: "同意授权",
					icon: "success",
				});
			} else {

				uni.showToast({
					title: "拒绝授权",
					icon: "error",
				});
			}
		},

		/**
		 * 获取隐私协议授权信息
		 * @returns {object} {needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》'}
		 */
		getPrivacySetting() {
			const res = {
				needAuthorization: false,
				privacyContractName: "基础库过低，不需要授权",
			};
			if (!uni.getPrivacySetting) return res;
			return new Promise((resolve, reject) => {
				uni.getPrivacySetting({
					success(res) {
						resolve(res);
					},
					fail(err) {
						reject(err);
					},
				});
			});
		},
		async getClassifyList(pid) {
			let res = await auth.getClassifyList({pid})
			this.tabs = [{name:'热销推荐',id:0},...res]
			this.firstId = this.tabs[0].id
			// this.secondId = 0
			// let secondTabs = await auth.getClassifyList({pid: res[0].id})
			// this.secondTabs = [{name:'全部',id:0},...secondTabs]
			this.secondTabs = [{name:'全部',id:0}]
			this.getGoodsList(this.firstId,this.secondId)
		},
		 // 获取我的页面信息
    async memberGetUserInfo() {
      let res = await auth.memberGetUserInfo();
      this.levelName = res.levelName 
    },
		  /**
     * 获取详情数据
     */
    async productGetOne(spuCode) {
      let res = await auth.productGetOne({spuCode})
      this.goodsInfo = res
			this.showSkuModal = true
    },
    close() {
      this.showSkuModal = false
    },
    // 获取分类菜单
		showSku(spuCode) {
			this.productGetOne(spuCode)
		},
		//点击一级分类
		async changeTab(index){
			this.active = index
			this.firstId = this.tabs[index].id
			this.pageNum = 1
			this.goodsList = []
			if(this.firstId) {
				// 请求二级分类的列表
				let secondTabs = await auth.getClassifyList({pid: this.firstId})
				this.secondTabs = [{name:'全部',id:0},...secondTabs]
			} else {
				this.secondTabs = [{name:'全部',id:0}]
			}
			this.secondId = 0
			this.getGoodsList(this.firstId,this.secondId)
		},
		changeSecTab(index){
			this.secondTab = index
			this.showModal = false
			this.goodsList = []
			this.pageNum = 1
			// 请求列表数据
			this.secondId = this.secondTabs[index].id
			this.getGoodsList(this.firstId,this.secondId)
		},
		async getGoodsList(classifyId,twoClassifyId) {
			let params = {
				classifyId,
				hotRecommend:classifyId==0?1:0,
				twoClassifyId,
				pageNum:this.pageNum,
				pageSize: 10
			}
			if(!classifyId) {delete params.classifyId}
			if(!twoClassifyId) {delete params.twoClassifyId}
			let goodObj = await auth.productGetList(params)
			this.goodsList = [...this.goodsList,...goodObj.data]
			this.goodsCount = goodObj.pages
			if(this.pageNum == this.goodsCount) {
				this.finished = true
			}

		},
		changeModal() {
			this.showModal = !this.showModal
		},
		goDetail(spuCode) {
			if(this.auth_token){
				uni.navigateTo({
					url: '/pages/FenLei/detail?spuCode=' + spuCode,
				})
			} else {
				uni.showToast({
					title:'登录查看商品详情~',
					icon:'none'
				})
			}
		},
    goSearch() {
      uni.navigateTo({
        url: '/pages/FenLei/search',

			})
    },
		onRefresh() {
			this.triggered = true;
			this.finished=  false
			this.pageNum = 1
			this.goodsList = []
			this.getGoodsList(this.firstId,this.secondId)
      console.log("onRefresh");
      setTimeout(() => {
        this.triggered = false;
      }, 1000);
    },
		onLower() {
			if(this.pageNum < this.goodsCount) {
				this.pageNum++
				this.getGoodsList(this.firstId,this.secondId)
			} else {
				this.finished = true
			}
		},
		async goOrder(obj) {
			this.showSkuModal =  false
			obj.skuObj.productId = this.goodsInfo.id
			console.log(obj)
			/**
			 * obj.type=1加入购物车
			 * 参数
			 * {
			 * "productAmount": 0,
					"productId": 0,
					"productSkuId": 0,
			 * }

			 obj.type=2商品详情页立即购买
			 进入提交商品订单页面source 订单创建来源，1：商品详情页，2：购物车列表

			 向下个页面传值
			 "productAmount": 0,
				"productId": 0,
				"productSkuId": 0,
				"source": 1,

				obj.type=3修改购物车中的商品数量
				参数
				{
					"productAmount": 0,
					"productSkuId": 0
				}
			 * 
			 * */ 
			switch (obj.type) {
				case 1:
					await auth.addOderCart(obj.skuObj)
          uni.showToast({title:'添加成功，在购物车等亲！'})
				break;
				case 2:
					uni.navigateTo({
						url: `/pages/GouWuChe/jieSuan?totalMoney=${obj.totalMoney}&skuObj=${JSON.stringify(obj.skuObj)}&source=1`
					})
				break;
				// case 3:
				// 	delete obj.skuObj.productId
				// 	await auth.changeCartNum(obj.skuObj)
			}

// 			{
//   "buyerRemarks": "",
//   "cardIds": [],
//   "offlinePayTime": "",
//   "payPic": "",
//   "payerName": "",
//   "userAddressId": 0
// }
			// 拿到要购买的商品信息和type
		}
  },
	// 已取消 https://hlgz-mall.oss-cn-hangzhou.aliyuncs.com/basic/50/0ca6eea7d637444cb4f755521116c9ae.png
	// 已完成 https://hlgz-mall.oss-cn-hangzhou.aliyuncs.com/basic/11/a1971223a04b42c5a07f7353dc66bcc0.png
	// 代付款 https://hlgz-mall.oss-cn-hangzhou.aliyuncs.com/basic/16/07bb7721df83476b92fc2bbec4940895.png
	// 待发货 https://hlgz-mall.oss-cn-hangzhou.aliyuncs.com/basic/10/22031cf479ea433daec0c47bf6665ca4.png
	// 待收货 https://hlgz-mall.oss-cn-hangzhou.aliyuncs.com/basic/5/48c345d6865f44e7bde56c3077e46cb3.png
}
</script>

<style lang="scss">
.index {
  height: 100%;
  // background-image: url('https://hlgz-mall.oss-cn-hangzhou.aliyuncs.com/basic/62/cc9dc9ae448f4e80944fa80094316d5d.png');
  
	.shop-list {
    height: 100%;
    display: flex;
    flex-direction: column;
    .search-top {
      display: flex;
			flex-direction: column;
      padding: 88rpx 36rpx 24rpx;
      .logo {
        width: 184rpx;
        height: 62rpx;
        margin-right: 24rpx;
      }
      .search {
				margin-top: 32rpx;
        flex: 1;
      }
    }
  .content {
    flex: 1;
    width: 100%;
    display: flex;
		background: linear-gradient( 180deg, #FFF5EE 0%, #FFFFFF 10%);
		border-radius: 16rpx 16rpx 0 0;
    padding-top: 24rpx;
    overflow: hidden;
    .tabs {
      font-size: 24rpx;
      border-radius: 0rpx 8rpx 0 0 ;
			border-right:  1px solid rgba(0,0,0,.04);
      overflow: auto;
      .tab {
				position: relative;
        width: 168rpx;
        height: 84rpx;
				padding: 16rpx 8rpx;
				margin:  8rpx 16rpx 8rpx 32rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				border-radius: 16rpx;
				span{
					color: #666;
					text-align: center;
					line-height: 44rpx;
				}
				.active {
					position: absolute;
					bottom: 12rpx;
					width: 54rpx;
					height: 12rpx;
				}
      }
      .act-tab{
				background: #FAFAFA;
				span{
					color: #333;
				}
      }
    }
		.second-tabs{
			flex: 1;
			overflow: hidden;
			display: flex;
			flex-direction: column;
			// margin: 20rpx;
			position: relative;
			.h3 {
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: #222222;
				line-height: 48rpx;
				padding: 20rpx;
			}
			.second-tabs-li {
				display: flex;
				align-items: flex-start;
				padding: 20rpx;
				.lis {
					display: flex;
					overflow-x: auto;
					.li {
						line-height: 36rpx;
						font-size: 24rpx;
						flex-shrink: 0;
						padding: 4rpx 20rpx;
						color: #333;
						background: #F5F7F9;
						border-radius: 8rpx;
						margin-right: 8rpx;
						margin-bottom: 8rpx;
					}
					.sec-act-tab {
						color: #FC6420;
						background: #FFF1F1;

					}
				}
				.icon {
					margin: 0 24rpx;
					margin-top: 14rpx;
				}

			}
			.show-second-tabs-li {
				position: absolute;
				left: 0;
				top: 88rpx;
				max-height: 300rpx;
				overflow: hidden;
				background: #fff;
				z-index: 99999999;
				.lis {
					display: block;
					max-height: 270rpx;
					overflow: auto;
					.li {
						float: left;
					}
				}
			}
		}
		.modals {
			position: absolute;
			left: 0;
			width: 100%;
			height: 100%;
			background: rgba(0,0,0,.3);
			overflow: hidden;
			z-index: 999;
		}
    .list {
      padding: 24rpx;
      flex: 1;
      overflow: auto;
      box-sizing: border-box;
      .shop-li {
        display: flex;
        margin-bottom: 32rpx;
        .img {
          width: 160rpx;
          height: 160rpx;
          border-radius: 16rpx;
        }
        .shop-content {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          margin-left: 16rpx;
          overflow: hidden;
          .title {
            color: #444;
            font-size: 28rpx;
            font-weight: 500;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
          .num {
						// text-decoration: line-through;
            color: #FC3D1C;
            font-size: 36rpx;
          }
					.kc {
						color: #666;
						font-size: 20rpx;
					}
          .bottom {
            display: flex;
            justify-content: space-between;
						.left {
							display: flex;
							.vip {
								width: 118rpx;
								height: 36rpx;
								display: flex;
								align-items: center;
								justify-content: center;
								font-size: 20rpx;
								background: linear-gradient( 153deg, #F6EFE5 0%, #FDEBDB 100%);
								img {
									width: 24rpx;
									height: 24rpx;
									margin-right: 6rpx;
								}
							}
							.logins{
								width: 180rpx;
							}
							.money {
								width: 112rpx;
								height: 36rpx;
								line-height: 36rpx;
								font-size: 20rpx;
								color: #FC3D1C;
              	background: #FFF6EF;
								text-align: center;
								border-radius: 0rpx 8rpx 8rpx 0rpx;
							}
						}
            .icon {
              width: 36rpx;
              height: 36rpx;
            }
          }
        }
      }
    }
  }
	.diver {
		margin-bottom: 60rpx;
		overflow: hidden;
	}
	.empty {
		width: 100%;
		height: 100%;
		overflow: hidden;
		display: flex;
		justify-content: center;
		align-items: center;
	}
  .mask {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,.4);
  }
  .modal {
    position: fixed;
    left: 10%;
    top: 300rpx;
    width: 80%;
    max-height: 800rpx;
    background: #fff;
    padding: 40rpx 32rpx;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    border-radius: 8rpx;
    box-sizing: border-box;
    z-index: 999;
    img {
      width: 40rpx;
      height: 40rpx;
      position: absolute;
      right: 0;
      top: 0;
      padding: 24rpx;
    }
    .title {
      text-align: center;
      font-size: 32rpx;
      font-weight: 500;
      margin-bottom: 24rpx;
    }
    .context {
      flex: 1;
      overflow: auto;
      font-size: 26rpx;
      line-height: 40rpx;
    }
  }
}
}
</style>
